package com.kuyu.wx;

import com.kuyu.json.ErrorEntity;
import com.kuyu.model.WxAccessToken;
import com.kuyu.model.WxFinalValue;
import com.kuyu.json.AccessTokenEntity;
import com.kuyu.json.JsonUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
//使用两个标签EnableScheduling和Scheduled开启定时任务
@Component
public class RefreshAccessTokenTask {
    private final SimpleDateFormat simpleDateFormat=new SimpleDateFormat("HH:mm:ss");
    //方法一：使用HttpClient第三依赖插件
   // @Scheduled(fixedRate = 1000*6000)
    public void refreshToken(){
        //业务逻辑代码，获取公众号access_token
        //token的有效时间为7200秒，我们每隔6000重新获取token
        HttpGet get=null;
        CloseableHttpResponse resp=null;
        HttpEntity entity=null;
        CloseableHttpClient client= HttpClients.createDefault();
        String url= WxFinalValue.ACCESS_TOKEN_URL;
        url=url.replace("APPID",WxFinalValue.APPID);
        url=url.replace("APPSECRET",WxFinalValue.APPSECRET);
        try {
            get=new HttpGet(url);
            resp= client.execute(get);
            int status=resp.getStatusLine().getStatusCode();
            if(status>=200&&status<300){
                entity=resp.getEntity();
                String content= EntityUtils.toString(entity);
                try {
                    AccessTokenEntity at= JsonUtils.jsonToPojo(content,AccessTokenEntity.class);
                    WxAccessToken.setAccessToken(at.getAccess_token());
                } catch (Exception e) {
                    ErrorEntity err=JsonUtils.jsonToPojo(content,ErrorEntity.class);
                    System.out.println("获取token异常："+err.getErrcode()+","+err.getErrmsg());
                    //发生异常，重新执行一次
                    refreshToken();
                }
            }
        }catch (ClientProtocolException ce){
            ce.printStackTrace();
        }
        catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                if(resp!=null) resp.close();
                if(client!=null) client.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        System.out.println("重新获取Token时间："+simpleDateFormat.format(new Date()));
    }
    //方法二，使用springboot自带请求方法，代码相对简洁
    @Scheduled(fixedRate = 1000*6000)
    public void refreshAccessToken(){
        RestTemplate restTemplate = new RestTemplate();
        String url= WxFinalValue.ACCESS_TOKEN_URL;
        url=url.replace("APPID",WxFinalValue.APPID);
        url=url.replace("APPSECRET",WxFinalValue.APPSECRET);
        String content = restTemplate.getForObject(url, String.class);
        try {
            AccessTokenEntity at= JsonUtils.jsonToPojo(content,AccessTokenEntity.class);
            WxAccessToken.setAccessToken(at.getAccess_token());
        } catch (Exception e) {
            ErrorEntity err=JsonUtils.jsonToPojo(content,ErrorEntity.class);
            System.out.println("获取token异常："+err.getErrcode()+","+err.getErrmsg());
            //发生异常，重新执行一次
            refreshAccessToken();
        }
    }
}
